package ru.jexp.rcp.supply.actions;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ui.IPartListener;
import org.eclipse.ui.ISelectionListener;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;

import ru.jexp.rcp.supply.img.JExpImageLink;
import ru.jexp.rcp.supply.mui.JExpSupplyMessages;

public class ActionNewPattern extends Action implements ISelectionListener,
		IPartListener {

	public static final String ID = "ru.jexp.rcp.supply.actions.actionnewpattern";

	private IPatternCommand activePart;

	public ActionNewPattern(IWorkbenchWindow window) {
		setId(ID);
		setActionDefinitionId(ID);
		setText(JExpSupplyMessages.New_pattern_action_text);
		setToolTipText(JExpSupplyMessages.New_pattern_action_tooltip);
		setImageDescriptor(JExpImageLink
				.getImageDescriptor(JExpImageLink.NEW_PATTERN));
		setEnabled(false);
		window.getSelectionService().addSelectionListener(this);
		window.getPartService().addPartListener(this);
	}

	@Override
	public void run() {
		activePart.pattern();
	}

	@Override
	public void selectionChanged(IWorkbenchPart part, ISelection selection) {
		setEnabled(activePart != null && activePart.canPattern());
	}

	@Override
	public void partActivated(IWorkbenchPart part) {
		if (part instanceof IPatternCommand) {
			activePart = (IPatternCommand) part;
		} else {
			activePart = null;
			setEnabled(false);
		}
	}

	@Override
	public void partClosed(IWorkbenchPart part) {
		if (part instanceof IPatternCommand) {
			if (activePart == part) {
				activePart = null;
				setEnabled(false);
			}
		}
	}

	@Override
	public void partDeactivated(IWorkbenchPart part) {
	}
	

	@Override
	public void partBroughtToTop(IWorkbenchPart part) {
		partActivated(part);
	}

	@Override
	public void partOpened(IWorkbenchPart part) {
	}

}
